<template>
  <div>
    <div class="flowChartType" v-if="!chartError">
      <el-radio-group v-model="chartType" @change="parseData">
        <el-radio-button label="Horizontal">{{$t('configLazyLoad.businessConfig.transverseFlowChart')}}</el-radio-button>
        <el-radio-button label="Vertical">{{$t('configLazyLoad.businessConfig.longitudinalFlowChart')}}</el-radio-button>
      </el-radio-group>
    </div>
    <div v-show="chartError" class="error font16">
      {{$t('configLazyLoad.businessConfig.flowChartError')}}
    </div>
    <div class="svgContainer" :class="{'align-items' : chartType === 'Horizontal'}">
      <div id="id1" style="overflow: scroll;">
      </div>
    </div>
    <flow-chart-details :stepinfo="currentStepInfo" :stepfields="currentStepFields" :flowData="currentFlow" @save="refresh"></flow-chart-details>
  </div>
</template>

<script>
  import mermaid from 'mermaid'
  // import 'mermaid/dist/mermaid.forest.css'
  import flowChartDetails from './flowChartDetails.vue'
  export default {
    name: 'bussinessFlowChat',
    data () {
      let self = this
      window.nodeClick = function (item) {
        let idArray = this.id.split('&')
        self.handlerNodeClick(idArray)
      }
      return {
        chartType: 'Horizontal',
        text: '',
        currentBusiness: {},
        currentFlow: {},
        currentStepInfo: '',
        currentStepFields: '',
        chartError: false
      }
    },
    props: {
      flowId: {
        type: String,
        default: ''
      }
    },
    components: {
      flowChartDetails
    },
    watch: {
      flowId () {
        if (this.flowId !== '' && this.flowId !== '1') {
          this.chartError = false
          this.$store.dispatch('getCache', {type: 'businessFlow', id: this.flowId}).then((res) => {
            this.currentFlow = res
            this.currentBusiness.data = res.steps
            this.parseData()
            this.currentStepFields = res.fields
          })
        }
      }
    },
    methods: {
      parseData () {
        if (this.chartType === 'Horizontal') {
          this.text = 'graph LR; \n '
        } else if (this.chartType === 'Vertical') {
          this.text = 'graph TD; \n '
        }
        let mermaidholder = document.getElementById('id1')
        if (!mermaidholder) {
          return
        }
        this.currentBusiness.data.forEach((item, index) => {
          if (item.isBegin) {
            this.analyCode(item)
          }
        })
        console.log(this.text)
//        let element = document.getElementById('id1')
//        mermaid.mermaidAPI.render('id1', this.text, function (svgCode) {
//          element.innerHTML = svgCode
//          element.firstChild.style.height = element.getAttribute('viewbox').split(' ')[3] + 'px'
//          element.firstChild.style.width = element.getAttribute('viewbox').split(' ')[2] + 'px'
//          element.style.overflow = 'auto'
//        })
//        let nodeArray = document.querySelectorAll('svg#id1 g.nodes g.node')
        mermaidholder.innerHTML = this.text
        mermaidholder.removeAttribute('data-processed')
        mermaid.init('#id1')
        mermaidholder.firstChild.style.height = mermaidholder.firstChild.getAttribute('viewBox').split(' ')[3] + 'px'
        mermaidholder.firstChild.style.width = mermaidholder.firstChild.getAttribute('viewBox').split(' ')[2] + 'px'
        mermaidholder.style.overflow = 'auto'
        let nodeArray = document.querySelectorAll('div#id1 g.nodes g.node')
        if (nodeArray.length > 0) {
          this.chartError = false
          nodeArray.forEach((item) => {
            item.addEventListener('click', window.nodeClick, false)
          })
        } else {
          this.chartError = true
        }
      },
      analyCode (item) {
        if (item.actions.length > 0) {
          item.actions.forEach((action) => {
            let actionid = item._id + '&' + action._id
            let actioncode
            if (item.isBegin) {
              actioncode = item._id + '["' + item.name + '"] ---' + actionid + '["' + action.name + '"]; \n'
            } else {
              actioncode = item._id + '("' + item.name + '") ---' + actionid + '["' + action.name + '"]; \n'
            }
            if (this.text.indexOf(actioncode) === -1) {
              this.text += actioncode
              this.text += 'class ' + actionid + ' systemSettingTaskAction; \n'
              this.text += 'click ' + item._id + ' nodeClick; \n'
              this.text += 'click ' + actionid + ' nodeClick; \n'
              this.currentBusiness.data.forEach((item1) => {
                if (item1._id === action.jumpTo) {
                  if (item1.systemFn && item1.systemFn === 'cancel') {
                    this.text += 'class ' + actionid + ' systemSettingTaskActionCancel; \n'
                  }
                  this.text += item._id + '&' + action._id + '["' + action.name + '"] -->' + item1._id + '("' + item1.name + '"); \n'
                  this.analyCode(item1)
                }
              })
            }
          })
        }
        if (this.text.indexOf('class ' + item._id + ' systemSettingTaskStep; \n') === -1) {
          this.text += 'class ' + item._id + ' systemSettingTaskStep; \n'
        }
      },
      handlerNodeClick (ids) {
        if (ids.length === 1) {
          this.$store.dispatch('queryBusinessFlowStep', {_id: ids[0]}).then((step) => {
            this.currentStepInfo = step.data
          })
        } else if (ids.length === 2) {
          this.$store.dispatch('queryBusinessFlowStep', {_id: ids[0]}).then((step) => {
            step.data.actions.forEach((item) => {
              if (item._id === ids[1]) {
                this.currentStepInfo = item
              }
            })
          })
        }
      },
      refresh () {
        this.$store.dispatch('getCache', {type: 'businessFlow', id: this.flowId, loadFromServer: true}).then((res) => {
          console.log(res)
          this.currentFlow = res
          this.currentBusiness.data = res.steps
          this.parseData()
          this.currentStepFields = res.fields
        })
      }
    },
    beforeMount () {
      this.$store.dispatch('getCache', {type: 'businessFlow', id: this.flowId}).then((res) => {
        this.currentFlow = res
        this.currentBusiness.data = res.steps
        this.parseData()
        this.currentStepFields = res.fields
      })
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .svgContainer
    height calc(100vh - 235px)
    width 100%
    /*overflow scroll*/
  .align-items
    display flex
    align-items center
  #id1
    width 100%
    max-width 100%!important
    margin 0 auto
    text-align center
    max-height calc(100vh - 255px)
  .flowChartType
    padding: 5px 0;
    text-align: right;
    margin-right: 20px;
  .error
    position absolute
    top 50%
    width 100%
    text-align center
</style>
